package leetcode;

public class LinkedListCyclePlus142 {
    class ListNode {
        int val;
        ListNode next;

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode detectCycle(ListNode head) {
        ListNode h = head;
        ListNode t = head;
        while (h != null && h.next != null) {
            h = h.next.next;
            t = t.next;
            if (t == h) {
                t = head;
                while (t != h) {
                    t = t.next;
                    h = h.next;
                }
                return t;
            }
        }
        return null;
    }
}
